package com.liangtian.mdm.material.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.material.model.WlTjfx;
import com.liangtian.mdm.material.service.WlTjfxService;

@Controller
@RequestMapping("/wltjfx")
public class WlTjfxController extends BaseController {
    @Autowired
    private WlTjfxService wlTjfxService;

    /**
     * 获取时间范围
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/getDateRange", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getDateRange(WlTjfx cond) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("rows", getDateRangeList(cond));// JSONArray
            jsonObject.put("success", true);//
        } catch (Exception e) {
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
            e.printStackTrace();
        }
        return jsonObject;
    }

    /**
     * 按创建时间统计,查询范围wf_wl表
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/getTjfxListByCond", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getTjfxListByCond(WlTjfx cond) {
        JSONObject jsonObject = new JSONObject();
        JSONArray arr = new JSONArray();
        //--对结束时间无条件加时间后缀
        cond.setEndTime(cond.getEndTime() + " 23:59:59");
        try {
            List<WlTjfx.WlTjfxResult> resultList = null;
            //--对取出来的数据根据需要进行分组，即将list转成map
            Map<String, List<WlTjfx.WlTjfxResult>> map = new LinkedHashMap<String, List<WlTjfx.WlTjfxResult>>();
            if ("1".equals(cond.getType())) {
                resultList = wlTjfxService.getTjfxByCreateTime(getDateRangeList(cond), cond);
                JSONObject child = new JSONObject();
                arr.add(child);
                for (WlTjfx.WlTjfxResult obj : resultList) {
                    child.put(obj.getTime_str(), obj.getCount_str());
                }
            } else if ("2".equals(cond.getType())) {
                resultList = wlTjfxService.getTjfxByDlCreateTime(getDateRangeList(cond), cond);
                for (WlTjfx.WlTjfxResult result : resultList) {
                    String dlCode = result.getDl_code();
                    String dlDesc = result.getDl_desc();
                    if (map.containsKey(dlCode + "@@" + dlDesc)) {
                        map.get(dlCode + "@@" + dlDesc).add(result);
                    } else {
                        List<WlTjfx.WlTjfxResult> tmpList = new ArrayList<WlTjfx.WlTjfxResult>();
                        tmpList.add(result);
                        map.put(dlCode + "@@" + dlDesc, tmpList);
                    }
                }
                //--对map进行迭代，同一个key【即大类】将所有的时间信息从多行合并成1行，便于页面展示
                Iterator<String> iter = map.keySet().iterator();
                while (iter.hasNext()) {
                    String dl = iter.next();
                    //--每个大类创建1个JSON对象，意思为1个大类展示表格中的1行。
                    JSONObject child = new JSONObject();
                    arr.add(child);
                    child.put("dl_code", dl.split("@@")[0]);//--put 大类列
                    child.put("dl_desc", dl.split("@@")[1]);//--put 大类列

                    List<WlTjfx.WlTjfxResult> tmpList = map.get(dl);
                    for (WlTjfx.WlTjfxResult obj : tmpList) {
                        child.put(obj.getTime_str(), obj.getCount_str());
                    }
                }
            } else if ("3".equals(cond.getType())) {
                resultList = wlTjfxService.getTjfxByCUserCreateTime(getDateRangeList(cond), cond);
                for (WlTjfx.WlTjfxResult result : resultList) {
                    String userAccount = result.getUser_account();
                    String userName = result.getUser_name();
                    if (map.containsKey(userAccount + "@@" + userName)) {
                        map.get(userAccount + "@@" + userName).add(result);
                    } else {
                        List<WlTjfx.WlTjfxResult> tmpList = new ArrayList<WlTjfx.WlTjfxResult>();
                        tmpList.add(result);
                        map.put(userAccount + "@@" + userName, tmpList);
                    }
                }
                //--对map进行迭代，同一个key【即大类】将所有的时间信息从多行合并成1行，便于页面展示
                Iterator<String> iter = map.keySet().iterator();
                while (iter.hasNext()) {
                    String user = iter.next();
                    //--每个用户创建1个JSON对象，意思为1个大类展示表格中的1行。
                    JSONObject child = new JSONObject();
                    arr.add(child);
                    child.put("user_account", user.split("@@")[0]);//--put 大类列
                    child.put("user_name", user.split("@@")[1]);//--put 大类列

                    List<WlTjfx.WlTjfxResult> tmpList = map.get(user);
                    for (WlTjfx.WlTjfxResult obj : tmpList) {
                        child.put(obj.getTime_str() + "_count", obj.getCount_str());
                        child.put(obj.getTime_str() + "_fail", obj.getFail_str());
                        child.put(obj.getTime_str() + "_successPercent", obj.getSuccess_percent());
                    }
                }
            } else if ("4".equals(cond.getType())) {
                resultList = wlTjfxService.getTjfxByAUserApproveTime(getDateRangeList(cond), cond);
                for (WlTjfx.WlTjfxResult result : resultList) {
                    String userAccount = result.getUser_account();
                    String userName = result.getUser_name();
                    if (map.containsKey(userAccount + "@@" + userName)) {
                        map.get(userAccount + "@@" + userName).add(result);
                    } else {
                        List<WlTjfx.WlTjfxResult> tmpList = new ArrayList<WlTjfx.WlTjfxResult>();
                        tmpList.add(result);
                        map.put(userAccount + "@@" + userName, tmpList);
                    }
                }
                //--对map进行迭代，同一个key【即大类】将所有的时间信息从多行合并成1行，便于页面展示
                Iterator<String> iter = map.keySet().iterator();
                while (iter.hasNext()) {
                    String user = iter.next();
                    //--每个用户创建1个JSON对象，意思为1个大类展示表格中的1行。
                    JSONObject child = new JSONObject();
                    arr.add(child);
                    child.put("user_account", user.split("@@")[0]);//--put 大类列
                    child.put("user_name", user.split("@@")[1]);//--put 大类列

                    List<WlTjfx.WlTjfxResult> tmpList = map.get(user);
                    for (WlTjfx.WlTjfxResult obj : tmpList) {
                        child.put(obj.getTime_str() + "_count", obj.getCount_str());
                        child.put(obj.getTime_str() + "_maxday", obj.getMaxday_str());
                        child.put(obj.getTime_str() + "_avgday", obj.getAvgday_str());
                    }
                }
            }

            jsonObject.put("rows", arr);// JSONArray
            jsonObject.put("success", true);//
        } catch (Exception e) {
            jsonObject.put("success", false);
            jsonObject.put("msg", e.getMessage());
            e.printStackTrace();
        }
        return jsonObject;
    }

    private List<String> getDateRangeList(WlTjfx cond) throws ParseException {
        List<String> allTimeRangeList = null;
        //--下面的日期范围格式必须和后台查询出来的结果集保持一致，否则列表页面无法展示数据。比如季度，表头格式为2018-1代表一季度。后台查询数据也得是2018-1这样的格式。
        if ("month".equals(cond.getMode())) {
            allTimeRangeList = getMonthBetween(cond.getStartTime(), cond.getEndTime());
        } else if ("season".equals(cond.getMode())) {
            allTimeRangeList = getSeasonBetween(cond.getStartTime(), cond.getEndTime());
        } else if ("year".equals(cond.getMode())) {
            allTimeRangeList = getYearBetween(cond.getStartTime(), cond.getEndTime());
        }
        return allTimeRangeList;
    }

    private List<String> getMonthBetween(String startDate, String endDate) throws ParseException {
        List<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(startDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(endDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    private List<String> getSeasonBetween(String startDate, String endDate) throws ParseException {
        //--先换算成月份列表
        List<String> monthResult = getMonthBetween(startDate, endDate);
        //--存储季度列表
        List<String> seasonResult = new ArrayList<String>();
        //--在进行遍历，凡事月份数位于1-3之间，则算作一季度、同理4-6，算作二季度，等等。
        for (String str : monthResult) {
            String seasonStr = null;
            if (str.endsWith("01") || str.endsWith("02") || str.endsWith("03")) {
                seasonStr = str.split("-")[0] + "-1";    //--年份加上季度1
            } else if (str.endsWith("04") || str.endsWith("05") || str.endsWith("06")) {
                seasonStr = str.split("-")[0] + "-2";    //--年份加上季度2
            } else if (str.endsWith("07") || str.endsWith("08") || str.endsWith("09")) {
                seasonStr = str.split("-")[0] + "-3";    //--年份加上季度3
            } else {
                seasonStr = str.split("-")[0] + "-4";    //--年份加上季度4
            }
            if (!seasonResult.contains(seasonStr))
                seasonResult.add(seasonStr);
        }
        return seasonResult;
    }

    private List<String> getYearBetween(String startDate, String endDate) throws ParseException {
        //--先换算成月份列表
        List<String> monthResult = getMonthBetween(startDate, endDate);
        //--存储年度列表
        List<String> yearResult = new ArrayList<String>();
        for (String str : monthResult) {
            String yearStr = str.split("-")[0];

            if (!yearResult.contains(yearStr))
                yearResult.add(yearStr);
        }
        return yearResult;
    }
}

